<template>
  <div class="form-container">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button @click="btn">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    var valdateModile = (rule,value,callback) =>{
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if(!reg.test(value)){
        callback(new Error('请输入合法的手机号'))
      }else{
        callback()
      }
    }
    return {
      form: {
        username: "",
        password: "123456",
        mobile:'110'
      },
      //校验
      rules: {
        //校验用户名
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        //校验密码
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 9 到 16 个字符", trigger: "blur" },
        ],
         mobile: [
           { required: true, message: "请输入用手机号", trigger: "blur" },
          // { min: 6, max: 16, message: "长度在 9 到 16 个字符", trigger: "blur" },
          { validator: valdateModile, trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      console.log("submit!");
      this.$refs['form'].validate(valid =>{//this.$refs获取dom元素
        console.log(valid);
        if(valid){
          alert('校验成功')
        }else{
          alert('校验失败')
        }
      })
    },
    btn(){
      this.$refs['form'].resetFields()
    }
  },
};
</script>

<style scoped>
.form-container {
  width: 600px;
}
</style>